package com.controller;

import com.service.UserService;
import com.service.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class AddUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1 设置编码方式
        request.setCharacterEncoding("utf-8");
        //2 获取登录数据
        final Map<String, String[]> parameterMap = request.getParameterMap();
        User user = new User();
        //3 封装数据
        try {
            BeanUtils.populate(user,parameterMap);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        //4 调用UserService保存数据
        ServletContext servletContext = this.getServletContext();
        final WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        UserService userService = (UserService) webApplicationContext.getBean("userService");;
        int i = 0;
        try {
            i = userService.addUser(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (i == 1)
        {
            //5 重新跳转到展示界面
//        request.getRequestDispatcher("/UserListServlet");
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        }
        else
        {
            response.sendRedirect(request.getContextPath()+"/add.jsp");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
